package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.system.domain.SysMenuFavorite;
import com.ruoyi.system.mapper.SysMenuFavoriteMapper;
import com.ruoyi.system.service.ISysMenuFavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户收藏菜单Service业务层处理
 * 
 * @author kuaidou
 * @date 2021-09-01
 */
@Service
public class SysMenuFavoriteServiceImpl implements ISysMenuFavoriteService 
{
    @Autowired
    private SysMenuFavoriteMapper sysMenuFavoriteMapper;

    /**
     * 查询用户收藏菜单
     * 
     * @param id 用户收藏菜单ID
     * @return 用户收藏菜单
     */
    @Override
    public SysMenuFavorite selectSysMenuFavoriteById(Long id)
    {
        return sysMenuFavoriteMapper.selectSysMenuFavoriteById(id);
    }

    /**
     * 查询用户收藏菜单列表
     * 
     * @param sysMenuFavorite 用户收藏菜单
     * @return 用户收藏菜单
     */
    @Override
    public List<SysMenuFavorite> selectSysMenuFavoriteList(SysMenuFavorite sysMenuFavorite)
    {
        return sysMenuFavoriteMapper.selectSysMenuFavoriteList(sysMenuFavorite);
    }

    /**
     * 新增用户收藏菜单
     * 
     * @param sysMenuFavorite 用户收藏菜单
     * @return 结果
     */
    @Override
    public int insertSysMenuFavorite(SysMenuFavorite sysMenuFavorite)
    {
        sysMenuFavorite.setCreateTime(DateUtils.getNowDate());
        Long userId = ShiroUtils.getUserId();
        sysMenuFavorite.setUserId(userId);
        synchronized ("menu_sc_"+userId) {
            //如果数据库以经存在则删除（取消收藏）
            SysMenuFavorite fa=sysMenuFavoriteMapper.selectSysMenuFavoriteByMenuId(sysMenuFavorite.getMenuId());
            if(fa!=null) {
                return sysMenuFavoriteMapper.deleteSysMenuFavoriteById(fa.getId());
            }else {
                sysMenuFavorite.setCreateTime(DateUtils.getNowDate());
                return sysMenuFavoriteMapper.insertSysMenuFavorite(sysMenuFavorite);
            }
        }
    }

    /**
     * 修改用户收藏菜单
     * 
     * @param sysMenuFavorite 用户收藏菜单
     * @return 结果
     */
    @Override
    public int updateSysMenuFavorite(SysMenuFavorite sysMenuFavorite)
    {
        sysMenuFavorite.setUpdateTime(DateUtils.getNowDate());
        return sysMenuFavoriteMapper.updateSysMenuFavorite(sysMenuFavorite);
    }

    /**
     * 删除用户收藏菜单对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteSysMenuFavoriteByIds(String ids)
    {
        return sysMenuFavoriteMapper.deleteSysMenuFavoriteByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除用户收藏菜单信息
     * 
     * @param id 用户收藏菜单ID
     * @return 结果
     */
    @Override
    public int deleteSysMenuFavoriteById(Long id)
    {
        return sysMenuFavoriteMapper.deleteSysMenuFavoriteById(id);
    }
}
